package com.atguigu.flink10;

import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/2/29
 * 该案例演示了保存点
 */
public class Flink01_Savepoint {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        Configuration conf = new Configuration();
        //最终检查点
        //conf.set(ExecutionCheckpointingOptions.ENABLE_CHECKPOINTS_AFTER_TASKS_FINISH, false);
        //StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);

        //检查点相关的设置
        //启用检查点 interval:多长时间做一次检查点  CheckpointingMode:指定barrier对齐是精准一次还是至少一次
        //env.enableCheckpointing(5000L);
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        CheckpointConfig checkpointConfig = env.getCheckpointConfig();

        //设置状态后端
        //env.setStateBackend(new HashMapStateBackend());
        //设置检查点存储路径
        //checkpointConfig.setCheckpointStorage(new JobManagerCheckpointStorage());
        checkpointConfig.setCheckpointStorage("hdfs://hadoop102:8020/ck");
        //检查点模式（CheckpointingMode）
        //checkpointConfig.setCheckpointingMode(CheckpointingMode.AT_LEAST_ONCE);

        //超时时间（checkpointTimeout）
        checkpointConfig.setCheckpointTimeout(60000L);
        //最小间隔时间（minPauseBetweenCheckpoints）
        checkpointConfig.setMinPauseBetweenCheckpoints(2000L);

        //最大并发检查点数量（maxConcurrentCheckpoints）
        //checkpointConfig.setMaxConcurrentCheckpoints(1);

        //开启外部持久化存储（enableExternalizedCheckpoints）---Job取消后，检查点是否保留
        checkpointConfig.setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //checkpointConfig.setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.DELETE_ON_CANCELLATION);

        //开启非对齐检查点
        //checkpointConfig.enableUnalignedCheckpoints();

        //对齐检查点超时时间（alignedCheckpointTimeout）
        //checkpointConfig.setAlignedCheckpointTimeout(Duration.ofSeconds(10));

        //设置检查点允许出错次数
        //checkpointConfig.setTolerableCheckpointFailureNumber(3);

        //Flink的容错设置----设置重启策略  默认重启Integer.MAX_VALUE
        //env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));

        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));

        //执行操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguigu");

        //通用增量 checkpoint (changelog)
        //env.enableChangelogStateBackend(true);

        env
                .socketTextStream("hadoop102",8888).uid("socket_id")
                //通过lambda表达式创建接口实现类对象
                .flatMap(
                        (String lineStr, Collector<Tuple2<String, Integer>> out) -> {
                            String[] words = lineStr.split(" ");
                            for (String word : words) {
                                out.collect(Tuple2.of(word,1));
                            }
                        }
                ).uid("flat_map_id")
                //.returns(new TypeHint<Tuple2<String, Integer>>() {})
                //注意：如果使用lambda表达式  会存在泛型擦除问题
                .returns(Types.TUPLE(Types.STRING,Types.INT))
                .keyBy(tup->tup.f0)
                .sum(1).uid("sum_id")
                .print().uid("print_id");

        env.execute();
    }
}
